#include "KEY.h"

// 按键初始化: 一脚接入电源负极,一脚接入PB6引脚
void KEY_Init(void) {
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

    GPIO_InitTypeDef GPIO_InitStruct;
    GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
    GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IPU; // 上拉输入
    GPIO_Init(GPIOB, &GPIO_InitStruct);
}

//利用AFIO映射KEY到线6
void KEY_AFIO_Map(void) {
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
    GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource6);
}

//配置EXTI
void KEY_EXTI_Init(void) {
    EXTI_InitTypeDef EXTI_InitStruct;
    EXTI_InitStruct.EXTI_Line = EXTI_Line6;
    EXTI_InitStruct.EXTI_LineCmd = ENABLE;
    EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
    EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Falling;
    EXTI_Init(&EXTI_InitStruct);
}

//配置NVIC
void KEY_NVIC_Init(void) {
    NVIC_InitTypeDef NVIC_InitStruct;
    NVIC_InitStruct.NVIC_IRQChannel = EXTI9_5_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
    NVIC_Init(&NVIC_InitStruct);
}

//写中断处理程序
void EXTI9_5_IRQHandler(void) {
    if (EXTI_GetITStatus(EXTI_Line6) == SET) {
        EXTI_ClearITPendingBit(EXTI_Line6);

        //while (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_6) == Bit_RESET);
        printf3("888\r\n");
        while (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_6) == Bit_SET) {
			printf3("123\r\n");
			Delay_ms(5000);
            int address = 0x0800F000;
            erasePage(address);
			printf3("erase\r\n");
			break;
        }
    }
}
